package com.yimi.yinhepda.views.unload_module;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.uce.pda.module.ConnectionResultLister;
import com.uce.pda.module.OneToMoreModule;
import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.table.MoveStockScanMasterTable;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.entity.bean.MoveStockScanChildEntity;
import com.yimi.yinhepda.entity.response.LoadInfo;
import com.yimi.yinhepda.entity.response.QueryLoadDetailBillcode;
import com.yimi.yinhepda.entity.response.QueryLoadDetailChildBillcode;
import com.yimi.yinhepda.event.CountEvent;
import com.yimi.yinhepda.utils.Common;
import com.yimi.yinhepda.utils.IntentUtils;
import com.yimi.yinhepda.utils.UcWaybillValidate;
import com.yimi.yinhepda.views.exceptionsUpload_module.ProblemBillUploadActivity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 运单扫描信息界面
 *
 * @author 000432
 */
public class UnloadCompareActivity extends BaseActivity implements View.OnTouchListener {
    TextView realWeightQty, meterageWeightQty, volume, unloadCompareTotalJian, unloadCompareTotalScaned, unloadCompareTotalNotScaned;

    EditText waybill_no;
    ListView listview;
    private ScrollView sv_compare;

    private List<UnloadCompareEntity> dataList;
    private UnloadCompareListViewAdapter adapter;

    private TextView num;
    /**
     * 装车还是卸车 1-装车，2-卸车，3-离线装车，4-离线卸车,5-移库装车，6-移库卸车
     */
    private int operTypeCode;
    private UnloadScanTableDao mUnloadScanTableDao;
    private String stowageNo, userCode, waybillNo, carNo;
    private Button btnChangeProblem;

    @Override
    public String getPageName() {
        return "运单扫描信息";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unload_compare);

        ((TextView) findViewById(R.id.title)).setText("运单扫描信息");
        num = findViewById(R.id.num);

        waybill_no = findViewById(R.id.activity_compare_waybill);
        realWeightQty = findViewById(R.id.activity_compare_realWeightQty);
        meterageWeightQty = findViewById(R.id.activity_compare_meterageWeightQty);
        volume = findViewById(R.id.activity_compare_volume);
        unloadCompareTotalJian = findViewById(R.id.unload_compare_total_jian);
        unloadCompareTotalScaned = findViewById(R.id.unload_compare_scaned);
        unloadCompareTotalNotScaned = findViewById(R.id.unload_compare_notScaned);
        listview = findViewById(R.id.activity_compare_listview);
        listview.setOnTouchListener(this);
        sv_compare = findViewById(R.id.sv_au_compare);
        sv_compare.setOnTouchListener(this);
        btnChangeProblem = findViewById(R.id.activity_compare_changeProblem);
        btnChangeProblem.setOnClickListener(this);

        dataList = new ArrayList<>();
        adapter = new UnloadCompareListViewAdapter(this, dataList);
        listview.setAdapter(adapter);
        findViewById(R.id.activity_compare_back).setOnClickListener(this);
        initData();
        //注册事件
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册事件
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(CountEvent countEvent) {
        num.setText(countEvent.getCount() + "");
    }

    private void initData() {
        //操作类型
        Bundle extras = getIntent().getExtras();
        operTypeCode = extras.getInt("operTypeCode");
        if (operTypeCode == 3 || operTypeCode == 4) {
            //离线装卸车
            String offlineTaskNo = extras.getString("offlineTaskNo");
            userCode = extras.getString("userCode");
            waybillNo = extras.getString("waybillNo");
            mUnloadScanTableDao = new UnloadScanTableDao();
            List<UnloadScanTable> scanDataList = mUnloadScanTableDao.getWaybillNo(offlineTaskNo, operTypeCode, userCode, waybillNo);

            waybill_no.setText(waybillNo);
            unloadCompareTotalJian.setText(scanDataList.size() + "");
            unloadCompareTotalScaned.setText(scanDataList.size() + "");
            for (UnloadScanTable item : scanDataList) {
                dataList.add(new UnloadCompareEntity(item.getChildWaybillNo(), "已扫描"));
            }
        } else if (operTypeCode == 5 || operTypeCode == 6) {
            //移库倒货装卸车
            btnChangeProblem.setVisibility(View.GONE);
            MoveStockScanMasterTable masterTable = (MoveStockScanMasterTable) getIntent().getSerializableExtra("scanMasterTable");
            waybill_no.setText(masterTable.getWaybillNo());
            unloadCompareTotalJian.setText(masterTable.getChildEntityList().size() + "");
            int count = 0;
            for (MoveStockScanChildEntity childEntity : masterTable.getChildEntityList()) {
                if (childEntity.getFlag() == 1) {
                    dataList.add(new UnloadCompareEntity(childEntity.getChildWaybillNo(), "已扫描"));
                    count++;
                } else {
                    dataList.add(new UnloadCompareEntity(childEntity.getChildWaybillNo(), "未扫描"));
                }
            }
            unloadCompareTotalScaned.setText(count + "");
        } else {
            if (operTypeCode == 1) {
                //装车
                final LoadInfo waybill = Common.mLoadInfo;
                if (waybill != null) {
                    //总件数大于已扫描数，查询快递服务器的明细子单号
                        if (UcWaybillValidate.validate(waybill.getWaybillNo())) { //判断是否是快递单号
                            for (QueryLoadDetailChildBillcode child : waybill.getChildList()) {
                                if (UcWaybillValidate.isUcChildWyabill(child.getChildWaybillNo())) {
                                    //快递子单，一票多件，通过主单查询子单明细
                                    OneToMoreModule.getInstance().querySonScanCodeDetail(waybill.getWaybillNo(), new ConnectionResultLister<List<String>>() {

                                        @Override
                                        public void getResult(int errorCode, List<String> strings) {
                                            if (strings != null && !strings.isEmpty()) {
                                                List<QueryLoadDetailChildBillcode> childList = new ArrayList<>();
                                                for (String childWaybill : strings) {
                                                    QueryLoadDetailChildBillcode childEntity = new QueryLoadDetailChildBillcode();
                                                    childEntity.setChildWaybillNo(childWaybill);
                                                    childEntity.setStowageNo(waybill.getStowageNo());
                                                    for (QueryLoadDetailChildBillcode child : waybill.getChildList()) {
                                                        if (child.getChildWaybillNo().equals(childWaybill)) {
                                                            if (child.getFlag() == 1) {
                                                                //设置子单已扫描状态
                                                                childEntity.setFlag(1);
                                                            }
                                                        }
                                                    }
                                                    childList.add(childEntity);
                                                }
                                                waybill.getChildList().clear();
                                                waybill.getChildList().addAll(childList);
                                                waybill.setSrcPiecesNum(childList.size());
                                            }
                                            //添加至明细列表
                                            addDataListfuncForLoad(waybill);
                                            //对刷新的列表重新进行排序
                                            Collections.sort(dataList);
                                            adapter.notifyDataSetChanged();
                                        }
                                    });
                                    return;
                                }
                            }
                    }
                    else{  //判断是否是快运
                        //添加至明细列表
                        addDataListfuncForLoad(waybill);
                    }

                }
            } else if (operTypeCode == 2) {
                //卸车
                QueryLoadDetailBillcode waybill = Common.mQueryLoadDetailBillcode;
                if (waybill != null) {
                    carNo = waybill.getCarNo();
                    stowageNo = waybill.getStowageNo();
                    waybill_no.setText(waybill.getWaybillNo());

                    unloadCompareTotalJian.setText(waybill.getSrcPiecesNum() + "");
                    unloadCompareTotalScaned.setText(waybill.getScanCount() + "");
                    unloadCompareTotalNotScaned.setText((waybill.getSrcPiecesNum() - waybill.getScanCount()) + "");
                    //实重
                    realWeightQty.setText(waybill.getWeight() + "kg");
                    //计费重量
                    meterageWeightQty.setText(waybill.getChargedWeight() + "kg");
                    volume.setText(waybill.getVolume() + "m³");

                    if (waybill.getChildList() != null) {
                        for (QueryLoadDetailChildBillcode item : waybill.getChildList()) {
                            if (item.getFlag() == 1) {
                                dataList.add(new UnloadCompareEntity(item.getChildWaybillNo(), "已扫描"));
                            } else {
                                dataList.add(new UnloadCompareEntity(item.getChildWaybillNo(), "未扫描"));
                            }
                        }
                    }
                }
            }
        }
        //对刷新的列表重新进行排序
        Collections.sort(dataList);
        adapter.notifyDataSetChanged();
    }

    /**
     * 添加至明细列表
     */
    private void addDataListfuncForLoad(LoadInfo waybill) {
        stowageNo = waybill.getStowageNo();
        waybill_no.setText(waybill.getWaybillNo());

        unloadCompareTotalJian.setText(waybill.getSrcPiecesNum() + "");
        unloadCompareTotalScaned.setText(waybill.getScanCount() + "");
        unloadCompareTotalNotScaned.setText((waybill.getSrcPiecesNum() - waybill.getScanCount()) + "");
        //实重
        realWeightQty.setText(waybill.getWeight() + "kg");
        //计费重量
        meterageWeightQty.setText(waybill.getChargedWeight() + "kg");
        volume.setText(waybill.getVolume() + "m³");

        if (waybill.getChildList() != null) {
            for (QueryLoadDetailChildBillcode item : waybill.getChildList()) {
                if (item.getFlag() == 1) {
                    dataList.add(new UnloadCompareEntity(item.getChildWaybillNo(), "已扫描"));
                } else {
                    dataList.add(new UnloadCompareEntity(item.getChildWaybillNo(), "未扫描"));
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_compare_back:
                finish();
                break;
            case R.id.activity_compare_changeProblem:
                Intent intent = new Intent(this, ProblemBillUploadActivity.class);
                intent.putExtra(IntentUtils.WAYBILLNO, waybill_no.getText().toString());
                intent.putExtra(IntentUtils.OPER_TYPE_CODE, operTypeCode);
                intent.putExtra(IntentUtils.STOWAGENO, stowageNo);
                if (carNo != null) {
                    intent.putExtra(IntentUtils.CAR_NO, carNo);
                }
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()) {
            case R.id.activity_compare_listview:
                listview.requestDisallowInterceptTouchEvent(true);
                break;
            default:
                sv_compare.requestDisallowInterceptTouchEvent(true);
                break;
        }
        return false;
    }
}

class UnloadCompareListViewAdapter extends BaseAdapter {
    private Context context;
    private List<UnloadCompareEntity> dataList;

    public UnloadCompareListViewAdapter(Context context, List<UnloadCompareEntity> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public int getCount() {
        return null != dataList ? dataList.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        UnloadCompareHolder holder;
        if (convertView == null) {
            holder = new UnloadCompareHolder();
            convertView = LayoutInflater.from(context).inflate(R.layout.activity_compare_listviewitem, parent, false);
            holder.childWaybillno = convertView.findViewById(R.id.compare_listitem_waybillno);
            holder.scaneState = convertView.findViewById(R.id.compare_listitem_scanestate);
            convertView.setTag(holder);
        } else {
            holder = (UnloadCompareHolder) convertView.getTag();
        }
        holder.childWaybillno.setText(dataList.get(position).getChildWaybillno());
        holder.scaneState.setText(dataList.get(position).getScaneState());
        if (dataList.get(position).getScaneState().equals("未扫描")) {
            convertView.setBackgroundColor(context.getResources().getColor(R.color.red));
        } else {
            convertView.setBackgroundColor(context.getResources().getColor(R.color.green));
        }
        return convertView;
    }
}

class UnloadCompareHolder {
    TextView childWaybillno;
    TextView scaneState;
}

class UnloadCompareEntity implements Comparable<Object>, Serializable {
    private String childWaybillno;
    private String scaneState;

    public UnloadCompareEntity(String childWaybillno, String scaneState) {
        this.childWaybillno = childWaybillno;
        this.scaneState = scaneState;
    }

    public UnloadCompareEntity() {
    }

    public String getChildWaybillno() {
        return childWaybillno;
    }

    public void setChildWaybillno(String childWaybillno) {
        this.childWaybillno = childWaybillno;
    }

    public String getScaneState() {
        return scaneState;
    }

    public void setScaneState(String scaneState) {
        this.scaneState = scaneState;
    }

    public int getType() {
        if (scaneState.equals("未扫描")) {
            return 0;
        } else {
            return 2000;
        }
    }

    @Override
    public int compareTo(Object o) {
        int result = this.childWaybillno.compareTo(((UnloadCompareEntity) o).childWaybillno);

        return (this.getType() - ((UnloadCompareEntity) o).getType() + result);
    }
}
